<?php

require_once 'Handler.php';

class LayeredContent_CacheHandler extends LayeredContent_Handler
{
	
	/**
	 * Specifies whether a valid cahce exists. Takes into account the cache
	 * expire configuration option
	 *
	 * @return boolean
	 */
	public function hasCache()
	{
		$cache = $this->getCachePath();
		$expire = $this->config->cache->expire;
		
		if (file_exists($cache) && (
			!$expire || filemtime($cache) + $expire > time())
		) {
			return true;
		}
		
		// no valid cache was found, we must "listen" for the ouput of this
		// script and save it for future calls
		ob_start(array($this, 'saveCache'));
		
		return false;
	}
	
	/**
	 * If the browser has this page already cached. This method will also send
	 * the Last-Modified and ETag headers and if the cache is current a 304 Not
	 * Modified header. We aren't using ETag because Yahoo! says it's not
	 * necessary or reliable.
	 * 
	 * @return boolean Whether the browser has it currently cached and the 304
	 * header was sent. Should stop execution if true.
	 */
	public function isCachedByBrowser()
	{
		$cache = $this->getCachePath();
		$modified = @filemtime($cache);
		$expire = $this->config->cache->expire;
		
		if (!$modified || ($expire && $modified + $expire < time()))
			return false;
		
		$fileModified = gmdate('D, d M Y H:i:s\G\M\T', $modified);
		
		// check the headers
		$lastModified = $_SERVER['HTTP_IF_MODIFIED_SINCE'];
		
		// send these either way
		header("Last-Modified: $fileModified");
		
		if ($lastModified && $lastModified == $fileModified) {
			header('HTTP/1.0 304 Not Modified');
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * Returns the contents of the cache to be sent to the browser. May also
	 * set the Content-Type header if needed.
	 *
	 * @return string The cache contents
	 */
	public function getCache()
	{
		return '';
	}
	
	
	public function saveCache($contents)
	{
		return $contents;
	}
	

	protected function getCachePath()
	{
		$path = $this->layeredContent
					 ->getHandler('urlHandler')
					 ->getFullPath(true, true);
		
		return $this->config->cache->path . $path;
	}
}
